package ar.com.jwa.commons.architecture.encription;

//-----------------------------------------------------------------------------
//StringEncrypter.java
//-----------------------------------------------------------------------------

/*
* =============================================================================
* Copyright (c) 1998-2009 Jeffrey M. Hunter. All rights reserved.
* 
* All source code and material located at the Internet address of
* http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and
* is protected under copyright laws of the United States. This source code may
* not be hosted on any other site without my express, prior, written
* permission. Application to host any of the material elsewhere can be made by
* contacting me at jhunter@idevelopment.info.
*
* I have made every effort and taken great care in making sure that the source
* code and other content included on my web site is technically accurate, but I
* disclaim any and all responsibility for any loss, damage or destruction of
* data or any other property which may arise from relying on it. I will in no
* case be liable for any monetary damages arising from such loss, damage or
* destruction.
* 
* As with any code, ensure to test this code in a development environment 
* before attempting to run it in production.
* =============================================================================
*/

//CIPHER / GENERATORS
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;


/**
* -----------------------------------------------------------------------------
* The following example implements a class for encrypting and decrypting
* strings using several Cipher algorithms. The class is created with a key and
* can be used repeatedly to encrypt and decrypt strings using that key.
* Some of the more popular algorithms are:
*      Blowfish
*      DES
*      DESede
*      PBEWithMD5AndDES
*      PBEWithMD5AndTripleDES
*      TripleDES
*/

public class EncryptionServiceImpl implements EncryptionService{

 private Cipher encryotionCipher;
 
 private Cipher decrypionCipher;

 /**
  * Constructor used to create this object.  Responsible for setting
  * and initializing this object's encrypter and decrypter Chipher instances
  * given a Secret Key and algorithm.
  * @param key        Secret Key used to initialize both the encrypter and
  *                   decrypter instances.
  * @param algorithm  Which algorithm to use for creating the encrypter and
  *                   decrypter instances.
  */
 public EncryptionServiceImpl(SecretKey key, String algorithm) {
     try {
         
    	 encryotionCipher = Cipher.getInstance(algorithm);
         
         decrypionCipher = Cipher.getInstance(algorithm);
         
         encryotionCipher.init(Cipher.ENCRYPT_MODE, key);
         
         decrypionCipher.init(Cipher.DECRYPT_MODE, key);
     
     } catch (NoSuchPaddingException e) {
         System.out.println("EXCEPTION: NoSuchPaddingException");
     } catch (NoSuchAlgorithmException e) {
         System.out.println("EXCEPTION: NoSuchAlgorithmException");
     } catch (InvalidKeyException e) {
         System.out.println("EXCEPTION: InvalidKeyException");
     }
 }

 
 /**
  * Takes a single String as an argument and returns an Encrypted version
  * of that String.
  * @param str String to be encrypted
  * @return <code>String</code> Encrypted version of the provided String
  */
 public String encrypt(String str) {
     try {
         // Encode the string into bytes using utf-8
         byte[] utf8 = str.getBytes("UTF8");

         // Encrypt
         byte[] enc = encryotionCipher.doFinal(utf8);

         // Encode bytes to base64 to get a string
         return new sun.misc.BASE64Encoder().encode(enc);

     } catch (BadPaddingException e) {
    	 
     } catch (IllegalBlockSizeException e) {
    	 
     } catch (UnsupportedEncodingException e) {
    	 
     } 
     
     return null;
 }


 /**
  * Takes a encrypted String as an argument, decrypts and returns the 
  * decrypted String.
  * @param str Encrypted String to be decrypted
  * @return <code>String</code> Decrypted version of the provided String
  */
 public String decrypt(String str) {

     try {

         // Decode base64 to get bytes
         byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

         // Decrypt
         byte[] utf8 = decrypionCipher.doFinal(dec);

         // Decode using utf-8
         return new String(utf8, "UTF8");

     } catch (BadPaddingException e) {
    	 
     } catch (IllegalBlockSizeException e) {
    	 
     } catch (UnsupportedEncodingException e) {
    	 
     } catch (IOException e) {
     }
     return null;
 }

}

